package com.zach.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class Path {
	public Path() {

	}

	/**
	 * return the real path of current class
	 * <P>if this is web project then return the directory of "WEB-INF/",<br/>
	 * if it's Java Project the return "bin/" directory
	 * <p>如果是Web项目返回的是WEB-INF/目录。果是Java项目返回的是bin目录
	 * */
	public String getWebPath() {
		String path = getPath();

		int index = path.lastIndexOf("/");
		path = path.substring(0, index - 7);
		// path = this.getClass().getResource("/").toString().substring(6);
		return path;
	}

	/**
	 * 返回java程序类文件所在目录(/classes/目录)
	 * return the java application's classes directory
	 * @return 返回java程序类文件所在目(/classes/)目录
	 */
	public String getPath() {
		String path;
		path = this.getClass().getResource("/").toString().substring(6);
//		path = this.getClass().getClassLoader().getResource(".").getPath();
//		if(path.startsWith("/")){
//			path = path.substring(1);
//		}
		return path;
	}

	/**
	 * 返回本网站应用程序根目录对应的实际目录名<p>
	 * the web project's relative root dir
	 * 
	 * @return 返回本网站应用程序根目录对应的实目录名<p>
	 */
	public String getWebBaseRealPath() {
		String strPath = getWebPath();
		strPath = strPath.substring(0, strPath.length() - 1);
		int index = strPath.lastIndexOf("/");
		strPath = strPath.substring(0, index + 1);
		return strPath;
	}
	/**
	 *get the root dir(like e:\ in window os)
	 * @param path 
	 * @return
	 */
	public static String getRootString(String path){
		File dir = new File(path);
		path = dir.getAbsolutePath();
		String root = path.substring(0, path.indexOf(File.separator)+1);
		return root;
	}
	/**
	 * get the root dir(like e:\ in window os)
	 * @param dir
	 * @return
	 */
	public static String getRootString(File dir){
		String path = dir.getAbsolutePath();
		String root = path.substring(0, path.indexOf(File.separator)+1);
		return root;
	}
	/**
	 * at the most time don't use this
	 * 
	 * @return 返回带有WebContent目录的目录形式
	 */
	public String getWebDevPath() {
		String str = getWebBaseRealPath();
		str = str + "WebContent/";
		return str;
	}

	/**
	 * read configuration from the given file in the classes directory 
	 * 
	 * @param fileName
	 *            which file the configuration in
	 * @param propertieName
	 *            the value you want to read
	 * @return the readed config data if not configured is null
	 */
	public String getConfigedValue(String fileName, String propertieName) {
		Properties prop = new Properties();
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(new File(getPath(), fileName));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
		try {
			prop.load(fis);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return	prop.getProperty(propertieName);
	}
}

